﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Microsoft.ServiceBus;
using SimpleServiceBus.Utilities;

namespace SimpleServiceBus.Endpoints.DotNetServiceBus.Transport
{
    public class WcfMessageEndpoint : BackgroundServiceBase, IWcfMessageQueue
    {
        private readonly MessageListener _listener = new MessageListener();
        private ServiceHost _host;
        private readonly Queue<Message> _messageQueue = new Queue<Message>();
        private readonly object _queueLock = new object();

        public WcfMessageEndpoint(Uri endpointUri)
        {
            if (endpointUri == null)
                throw new ArgumentNullException("endpointUri");

            EndpointUri = endpointUri;
        }

        public Uri EndpointUri { get; private set; }

        public Message GetNextMessage()
        {
            lock(_queueLock)
                return _messageQueue.Dequeue();
        }

        protected override void StartService()
        {
            _listener.MessageReceived += ListenerMessageReceived;
            _host = new ServiceHost(_listener);
            _host.AddServiceEndpoint(typeof (IOnewayReceiver),
                                    new NetTcpRelayBinding(
                                        EndToEndSecurityMode.Transport,
                                        RelayClientAuthenticationType.RelayAccessToken,
                                        false), EndpointUri);
            _host.Open();


        }

        protected override void ShutDownService()
        {
            if (_host != null)
            {
                try
                {
                    _host.Close();
                }
                catch (Exception)
                {
                    _host.Abort();
                }
            }
        }

        void ListenerMessageReceived(object sender, WcfMessageEventArgs e)
        {
            lock(_queueLock)
                _messageQueue.Enqueue(e.Message);
        }

        
    }
}
